package cn.itcast.ip_spring_boot_starter.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class IpCountService {
    @Autowired //哪个方法用这个依赖,就是那个方法提供request对象
    private HttpServletRequest httpServletRequest;
    private Map<String ,Integer> ipCountMap=new HashMap<>();
    public void count(){

        //统计ip的访问次数
        String ip=httpServletRequest.getRemoteAddr();

        Integer ipCount=ipCountMap.get(ip);
        if(ipCount==null){
            ipCountMap.put(ip,1);
        }else {
            ipCountMap.put(ip,ipCount+1);
        }
        System.out.println("ip 统计功能 被触发了"+ip+":"+ipCountMap.get(ip));
    }

    @Scheduled(cron = "0/5 * * * * ?") //秒，分，时，天，月，周 周不写,则根据天自动计算;5秒一次
    public void print(){
        System.out.println("ip访问监控记录:");
        for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
            String key=entry.getKey();
            Integer value=entry.getValue();
            System.out.println(key+":"+value);
        }
        System.out.println();
    }

    public static void main(String[] args) {
        new IpCountService().print();
    }
}
